<template lang="pug">
  v-dialog( v-model="active" fullscreen hide-overlay scrollable transition="dialog-bottom-transition")
    v-card
      slot(name="header")
        v-toolbar(dark, color='primary')
          v-btn(icon, dark, @click='cancel')
            v-icon close
          v-toolbar-title {{title}}
          v-spacer
          v-toolbar-items
            v-btn(dark, text, @click='reset' v-show="dirty") 重置
            v-btn(dark, text, @click='save') 保存
      v-card-text
        // AssetForm(ref="form", :asset="asset", @dirty="dirty = true")
        component(:is="currentForm" ref="form" :asset="asset" @dirty="dirty = true")
</template>
<script>
  import AssetForm from './asset_form'
  import AssetStockForm from '../asset_stock/asset_stock_form'

  export default {
    props: ['asset', 'formType'],
    methods: {
      toggle(title, isNew = false) {
        this.title = title
        this.isNew = isNew
        this.active = !this.active
      },
      reset() {
        this.$refs.form.reset()
        this.dirty = false
      },
      save() {
        if (!this.onceClick) {
          return
        }
        this.onceClick = false
        // in order to make v-comobox triggle onBlur event
        setTimeout(() => {
          this.$refs.form
              .save()
              .then(() => {
                if (this.isNew) {
                  this.$emit('refresh')
                }
              })
              .then(() => {
                this.active = false
                this.dirty = false
                this.onceClick = true
              })
              .catch(err => {
                this.onceClick = true
              })
        }, 200)
      },
      cancel() {
        this.active = false
        this.dirty = false
        this.$refs.form.reset()
      },
      showBodyScrollBar() {
        const body = document.body
        const scrollY = body.style.top
        body.style.position = ''
        body.style.top = ''
        window.scrollTo(0, parseInt(scrollY || '0') * -1)
      },
      hiddenBodyScrollBar() {
        const scrollY = window.scrollY
        const body = document.body
        this.winScrollY = `-${scrollY}px`
        body.style.position = 'fixed'
        body.style.top = this.winScrollY
      }
    },
    watch: {
      active(active) {
        active ? this.hiddenBodyScrollBar() : this.showBodyScrollBar()
      }
    },
    components: {AssetForm, AssetStockForm},
    computed: {},
    data() {
      let currentForm = this.formType === 'AssetForm' ? AssetForm : AssetStockForm
      return {
        currentForm,
        onceClick: true,
        title: '',
        isNew: false,
        active: false,
        dirty: false
      }
    }
  }
</script>